package state

import "fmt"

// vendingMachine 背景
type vendingMachine struct {
	hasItem state
	itemRequested state
	hasMoney state
	noItem state

	currentState state

	itemCount int
	itemPrice int
}

func NewVendingMachine(itemCount, itemPrice int) *vendingMachine {
	v := &vendingMachine{
		itemCount:     itemCount,
		itemPrice:     itemPrice,
	}
	hasItemState := &hasItemState{vendingMachine: v}
	itemRequestedState := &itemRequestedState{vendingMachine: v}
	hasMoneyState := &hasMoneyState{vendingMachine: v}
	noItemState := &noItemState{vendingMachine: v}

	v.setState(hasItemState)
	v.hasItem = hasItemState
	v.itemRequested = itemRequestedState
	v.hasMoney = hasMoneyState
	v.noItem = noItemState

	return v
}

func (v *vendingMachine) setState(state2 state) {
	v.currentState = state2
}

func (v *vendingMachine) AddItem(count int) error {
	return v.currentState.AddItem(count)
}

func (v *vendingMachine) RequestItem() error {
	return v.currentState.RequestItem()
}

func (v *vendingMachine) InsertMoney(money int) error {
	return v.currentState.InsertMoney(money)
}

func (v *vendingMachine) DispenseItem() error {
	return v.currentState.DispenseItem()
}

func (v *vendingMachine) incrementItemCount(count int) {
	fmt.Printf("Adding %d items\n", count)
	v.itemCount = v.itemCount + count
}
